import { useEffect, useState } from 'react';
import { Form, Row, Col, Input, Button, Table, Select, Tag, Modal } from 'antd';
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import DialogModalForm, { Item } from './DialogModalForm';

import systemUserApi from '../../../api/system/user';

const { confirm } = Modal;
const { Option } = Select;

export interface IRoles {
  id: number, name: string
}

function showPromiseConfirm() {
  confirm({
    title: 'Do you want to delete these items?',
    icon: <ExclamationCircleOutlined />,
    content: 'When clicked the OK button, this dialog will be closed after 1 second',
    onOk() {
      return new Promise((resolve, reject) => {
        setTimeout(Math.random() > 0.5 ? resolve : reject, 1000);
      }).catch(() => console.log('Oops errors!'));
    },
    onCancel() {},
  });
}

// type 
// const data: any = [];
// for (let i = 0; i < 46; i++) {
//   data.push({
//     key: i,
//     userName: `Edward King ${i}`,
//     nickName: '大老虎',
//     phone: 32,
//     roles: [{
//       id: 1,
//       name: '超级管理员'
//     }],
//     isEnable: i % 2
//   });
// }

const User = () => {
  const roles: IRoles[] = [
    {
      id: 1,
      name: "超级管理员"
    },
    {
      id: 2,
      name: "管理员"
    }
  ]
  const [data, setData] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [state, setstate] = useState<Item | null>();
  const [modalTitle, setModalTitle] = useState("new");

  const handleSetIsModalVisible = (bool: boolean) => {
    setIsModalVisible(bool)
  }

  useEffect(() => {

    systemUserApi.list().then((res: any)=>{
      console.log(res.data)
      setData(res.data.items)
    })
    
  }, [])
  // const handleOk = () => {
  //   setConfirmLoading(true)
  //   console.log(formDialog.getFieldsValue())
  //   // setConfirmLoading(false)
  //   // setIsModalVisible(false);
  //   setTimeout(() => {
  //     setConfirmLoading(false)
  //   }, 1000)
  // };

  // const handleCancel = () => {
  //   setIsModalVisible(false);
  //   formDialog.resetFields();
  // };

  const remove = (record?: Item) => {
    showPromiseConfirm()
  }
  // 添加新用户
  const handleAddUser = () => {
    setModalTitle('new');
    setIsModalVisible(true);
    setstate(null);
  }
  // 编辑用户
  // const handleEdit = (record?: Partial<Item> & { key?: React.Key }) => {
    const handleEdit = (record: Item) => {
    setstate(record);
    setModalTitle('edit');
    setIsModalVisible(true);
  };

  const columns = [
    {
      title: '用户名',
      dataIndex: 'userName',
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
    },
    {
      title: '电话',
      dataIndex: 'phone',
    },
    {
      title: '角色',
      dataIndex: 'roles',
      render: (roles: IRoles[]) => (
        <>
          {roles.map((role: IRoles) => {
            return (
              <Tag color="blue" key={role.id}>
                {role.name}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '状态',
      dataIndex: 'isEnable',
      render: (isEnable: number) => {
        let value = '', color = 'geekblue';
        if (isEnable === 0) {
          value = '已禁用';
          color = 'volcano'
        } else if (isEnable === 1) {
          value = '启用';
        }
        return (
          <Tag color={color}>
            {value}
          </Tag>
        )
      }
    },
    {
      title: '创建人',
      dataIndex: 'updateUser',
    },
    {
      title: '最近更新时间',
      dataIndex: 'updateTime',
    },
    {
      title: '操作',
      dataIndex: 'action',
      render: (text: any, record: Item) => <><Button type="link" icon={<EditOutlined />} size="small" onClick={() => handleEdit(record)}>编辑</Button><Button type="link" danger icon={<DeleteOutlined />} size="small" onClick={() => remove(record)}>删除</Button></>
    }
  ];

  const AdvancedSearchForm = () => {
    const [formSearch] = Form.useForm();

    const handleFilter = (values: any) => {
      console.log('Received values of formSearch: ', values);
    };

    return (
      <Form
        form={formSearch}
        name="advanced_search"
        className="ant-advanced-search-form mb-20"
        onFinish={handleFilter}
        initialValues={{ isEnable: 2 }}
      >
        <Row gutter={24}>
          <Col span={8}>
            <Form.Item
              name="userName"
              label="用户名"
            >
              <Input placeholder="请输入用户名" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="nickName"
              label="昵称"
            >
              <Input placeholder="请输入昵称" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="phone"
              label="电话"
            >
              <Input placeholder="请输入电话" />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="roles"
              label="角色"
            >
            <Select placeholder="请选择角色" mode="multiple" allowClear>
              {
                roles.map((role: IRoles)=> (
                  <Option value={role.id} key={role.id}>{role.name}</Option>
                ))
              }
            </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="isEnable"
              label="状态"
            >
              <Select>
                <Option value={2}>所有状态</Option>
                <Option value={1}>启用</Option>
                <Option value={0}>已禁用</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={24} style={{ textAlign: 'right' }}>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              style={{ margin: '0 8px' }}
              onClick={() => {
                formSearch.resetFields();
              }}
            >
              重置
            </Button>
            <Button
              style={{ margin: '0 8px' }}
              type="primary" ghost
              onClick={() => {handleAddUser()}}
            >
              增加
            </Button>
              <Button
                danger
                onClick={() => {remove()}}
              >
                删除
            </Button>
          </Col>
        </Row>
      </Form>
    );
  };

  const onSelectChange = (selectedRowKeys: any) => {
    setSelectedRowKeys(selectedRowKeys)
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: (changableRowKeys: any) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((key: any, index: number) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: (changableRowKeys: any) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((key: any, index: number) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  const pagination = {
    // showSizeChanger: true,
    // showQuickJumper: true,
    total: 100, // 数据总数
    current: 1,
    pageSize: 20
    // pageSize: parseInt(pageSize), // 每页条数
    // current: parseInt(pageNum), // 当前页码
    // showTotal: ((total) => {
    //   return `共 ${total} 条`;
    // })
  }

  return (<>
    <AdvancedSearchForm />
    <Table 
      rowSelection={rowSelection} 
      columns={columns} 
      dataSource={data} 
      rowKey={(record:any)=>(record.id)}
      pagination={pagination}
    />
    
    {
      isModalVisible && <DialogModalForm isModalVisible={isModalVisible} handleSetIsModalVisible={handleSetIsModalVisible} modalTitle={modalTitle} record={state} roles={roles} />
    }
  </>)
}

export default User;
